package pers.amos.eshop.thread;

import pers.amos.eshop.request.Request;
import pers.amos.eshop.request.RequestQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author amos wong
 * @create 2020-11-14 3:16 下午
 * <p>
 * 请求处理线程池：使用单例模式
 */

public class RequestProcessorThreadPool {

    /**
     * 定义一个容量为10的线程池
     */
    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public RequestProcessorThreadPool() {
        RequestQueue requestQueue = RequestQueue.getInstance(); // 获取内存队列
        for (int i = 0; i < 10; i++) {
            // 创建容量为100的阻塞队列
            ArrayBlockingQueue<Request> blockingQueue = new ArrayBlockingQueue<>(100);
            requestQueue.addQueue(blockingQueue); // 将该阻塞队列添加到内存队列中
            threadPool.submit(new RequestProcessorThread(blockingQueue));
        }
    }


    /**
     * 这里采用静态内部类的方式保证线程安全
     */
    private static class Singleton {

        private static RequestProcessorThreadPool instance;

        static {
            instance = new RequestProcessorThreadPool();
        }

        public static RequestProcessorThreadPool getInstance() {
            return instance;
        }
    }

    /**
     * JVM保证并发线程安全
     * 无论有多少个线程执行，静态内部类只会初始化一次
     * @return
     */
    public static RequestProcessorThreadPool getInstance() {
        return Singleton.getInstance();
    }

    /**
     * 初始化的便捷方法，直接调用上面的getInstance()方法
     * @return
     */
    public static RequestProcessorThreadPool init() {
        return getInstance();
    }
}
